//
//  easyMeshAP.cpp
//  
//
//  Created by Bill Gray on 7/26/16.
//
//

#include <Arduino.h>
#include<ESP8266WiFi.h>

extern "C" {
#include "user_interface.h"
#include "espconn.h"
}

#include "easyMesh.h"


// AP functions
//***********************************************************************
void ICACHE_FLASH_ATTR easyMesh::apInit( void  ) {
//    String password( MESH_PASSWORD );
    
    uint8_t third = _chipId & 0xFF;
    IPAddress ip(192, 168, third, 1);
    IPAddress gateway(192, 168, third, 1);
    IPAddress netmask(255, 255, 255, 0);

    if ( !WiFi.softAPConfig(ip, gateway, netmask) ) {
        debugMsg( ERROR, "WiFi.softAPConfig() failed\n");
    }
    
    if ( !WiFi.softAP(_mySSID, _meshPassword)) {
        debugMsg( ERROR, "WiFi.softAP() failed\n");
    }

    // establish AP tcpServers
    tcpServerInit( _meshServerConn, _meshServerTcp, meshConnectedCb, _meshPort );
}

//***********************************************************************
void ICACHE_FLASH_ATTR easyMesh::tcpServerInit(espconn &serverConn, esp_tcp &serverTcp, espconn_connect_callback connectCb, uint32 port) {
    
    debugMsg( GENERAL, "tcpServerInit():\n");
    
    serverConn.type = ESPCONN_TCP;
    serverConn.state = ESPCONN_NONE;
    serverConn.proto.tcp = &serverTcp;
    serverConn.proto.tcp->local_port = port;
    espconn_regist_connectcb(&serverConn, connectCb);
    sint8 ret = espconn_accept(&serverConn);
    if ( ret == 0 )
        debugMsg( STARTUP, "AP tcp server established on port %d\n", port );
    else
        debugMsg( ERROR, "AP tcp server on port %d FAILED ret=%d\n", port, ret);
    
    return;
}
